﻿using ServerUtils;
using System;
using System.Threading.Tasks;

namespace DemoServiceLibrary
{
    public class GetServerInfoOperation : IOperation<GetServerInfoResult>
    {
        private const string name = "GetServerInfo";
        private readonly string parameter;

        private readonly IServerInfoProvider serverInfoProvider;

        public GetServerInfoOperation(IServerInfoProvider serverInfoProvider, string parameter)
        {
            this.serverInfoProvider = serverInfoProvider;
            this.parameter = parameter;
        }
        
        public long OperationId { get; set; }

        public string Name
        {
            get { return name; }
        }

        public object Request
        {
            get { return this.parameter; }
        }

        public GetServerInfoResult Execute()
        {
            // simulate a server error
            if (this.parameter == "server-error-test")
            {
                throw new Exception(this.parameter);
            }

            // simulate a failed operation
            if (this.parameter == "failed-test")
            {
                return new GetServerInfoResult { ResultType = OperationResultType.Failed, Message = this.parameter};
            }

            ServerInfo serverInfo = this.serverInfoProvider.GetServerInfo();
            return new GetServerInfoResult { ResultType = OperationResultType.Succeed, Data = serverInfo };
        }

        public Task<GetServerInfoResult> ExecuteAsync()
        {
            // This implementation is just for the demo. A real Async method will call another async methods using await.
            return Task.Run(() =>
                {
                    return this.Execute();
                });
        }
    }
}
